package com.miui.theme.custom.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miui.theme.custom.data.ConfigDataStore
import com.miui.theme.custom.utils.MySQLHelper
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

// 状态：加载中、成功、失败
enum class DataState { Idle, Loading, Success, Error }

class TableCrudViewModel(configDataStore: ConfigDataStore) : ViewModel() {

    private val _dataState = MutableStateFlow(DataState.Idle)
    val dataState = _dataState.asStateFlow()

    // 存储列名
    private val _columns = MutableStateFlow<List<String>>(emptyList())
    val columns = _columns.asStateFlow()

    // 存储数据行，每行是一个 Map<列名, 值>
    private val _data = MutableStateFlow<List<Map<String, Any?>>>(emptyList())
    val data = _data.asStateFlow()

    private val _error = MutableStateFlow<String?>(null)
    val error = _error.asStateFlow()

    private lateinit var helper: MySQLHelper
    private var currentTable: String? = null

    // 修复 lateinit 崩溃的关键
    private val initializationJob: Job

    init {
        // 启动一个异步任务来初始化 helper
        initializationJob = viewModelScope.launch {
            val config = configDataStore.config.first()!!
            helper = MySQLHelper(config)
        }
    }

    /**
     * 加载表结构和数据
     */
    fun loadTableData(tableName: String) {
        currentTable = tableName
        viewModelScope.launch {
            // 等待 init 协程执行完毕
            initializationJob.join()

            _dataState.value = DataState.Loading
            // 访问 helper 现在是安全的
            val result = helper.executeQuery("SELECT * FROM $tableName")
            if (result.isSuccess) {
                val rs = result.getOrThrow()
                try {
                    // 1. 获取列名
                    val metaData = rs.metaData
                    val columnList = mutableListOf<String>()
                    for (i in 1..metaData.columnCount) {
                        columnList.add(metaData.getColumnName(i))
                    }
                    _columns.value = columnList

                    // 2. 获取数据
                    val dataList = mutableListOf<Map<String, Any?>>()
                    while (rs.next()) {
                        val rowMap = mutableMapOf<String, Any?>()
                        for (colName in columnList) {
                            rowMap[colName] = rs.getObject(colName)
                        }
                        dataList.add(rowMap)
                    }
                    _data.value = dataList
                    _dataState.value = DataState.Success
                } catch (e: Exception) {
                    e.printStackTrace()
                    _error.value = "数据解析失败: ${e.message}"
                    _dataState.value = DataState.Error
                }
            } else {
                _error.value = "查询失败: ${result.exceptionOrNull()?.message}"
                _dataState.value = DataState.Error
            }
        }
    }

    /**
     * 刷新当前表的数据
     */
    fun refreshData() {
        currentTable?.let { loadTableData(it) }
    }

    /**
     * 插入数据
     * data: Map<列名, 要插入的值>
     */
    fun insertData(tableName: String, data: Map<String, String>) {
        viewModelScope.launch {
            // 确保 helper 已初始化
            initializationJob.join()

            _dataState.value = DataState.Loading
            val cols = data.keys.joinToString(", ")
            val values = data.values.joinToString(", ") { "'$it'" } // 简单处理，注意SQL注入风险
            val sql = "INSERT INTO $tableName ($cols) VALUES ($values)"

            val result = helper.executeUpdate(sql)
            if (result.isSuccess) {
                loadTableData(tableName) // 成功后刷新
            } else {
                _error.value = "插入失败: ${result.exceptionOrNull()?.message}"
                _dataState.value = DataState.Error
            }
        }
    }

    /**
     * 删除数据
     * primaryKey: 一个键值对，用于定位要删除的行
     */
    fun deleteData(tableName: String, primaryKey: Pair<String, Any?>) {
        viewModelScope.launch {
            // 确保 helper 已初始化
            initializationJob.join()

            _dataState.value = DataState.Loading
            val (keyColumn, keyValue) = primaryKey
            val valueStr = if (keyValue is String) "'$keyValue'" else keyValue.toString()
            val sql = "DELETE FROM $tableName WHERE $keyColumn = $valueStr"

            val result = helper.executeUpdate(sql)
            if (result.isSuccess) {
                loadTableData(tableName) // 成功后刷新
            } else {
                _error.value = "删除失败: ${result.exceptionOrNull()?.message}"
                _dataState.value = DataState.Error
            }
        }
    }

    /**
     * 更新数据
     * primaryKey: 定位行的主键
     * data: Map<列名, 要更新的值> (注意：这里假设 data 包含了所有字段的新值)
     */
    fun updateData(tableName: String, primaryKey: Pair<String, Any?>, data: Map<String, String>) {
        viewModelScope.launch {
            initializationJob.join()
            _dataState.value = DataState.Loading

            val (keyColumn, keyValue) = primaryKey

            // 构建 SET 子句
            val setClause = data
                .filterKeys { it != keyColumn } // 过滤掉主键
                .map { "${it.key} = '${it.value}'" } // 简单处理，注意SQL注入
                .joinToString(", ")

            val valueStr = if (keyValue is String) "'$keyValue'" else keyValue.toString()
            val sql = "UPDATE $tableName SET $setClause WHERE $keyColumn = $valueStr"

            val result = helper.executeUpdate(sql)
            if (result.isSuccess) {
                loadTableData(tableName) // 成功后刷新
            } else {
                _error.value = "更新失败: ${result.exceptionOrNull()?.message}"
                _dataState.value = DataState.Error
            }
        }
    }
}